<?php
	function showDbError()
	{
		global $g_db;
		die("ADODB ERROR : <font color=red face='Arial'>" . $g_db->ErrorMsg()) . "</font>";
	}

	function da($arr_str)
	{
		echo "<pre>";
		print_r($arr_str);
		echo "</pre>";
	}

	function uaStrCompare($str1,$str2)
	{
		if (strcmp(trim($str1),trim($str2)) == 0) {
			return true;
		}else {
			return false;
		}
	}

	function getRadomStr($len=6,$recycle=1){
		
		$str.= 'ABCDEFGHJKMNPQRSTUVWXYabcdefghjkmnpqrstuvwxy';
		$str.= '123456789';
		
		$str = str_repeat($str,$recycle);
		return substr(str_shuffle($str),0,$len);
	}

	function setvar($name,$var)
	{
		global $smarty;
		$smarty->assign($name,$var);
	}

	function uaAssign($names)
	{
		global $smarty;
		if (is_array($names)) {
			foreach ($names as $smt_key=>$smt_val) {
				$smarty->assign($smt_key,$smt_val);
			}
		}
	}

	/**
	* @ifbackward 是否产生返回按钮
	*/
	function goto($url = "./index.php", $result = false, $msg = null, $otherparams = null, $ifbackward = true)
	{
		if ($result) {
			$url.="?result=success";
			if(isset($msg)) $url.="&message=".urlencode($msg);
		}
		if(isset($_SERVER['HTTP_REFERER'])){
			$forward = urlencode($_SERVER['HTTP_REFERER']);
			if(strpos($url, ".php?")) $url.="&return_forward=".$forward;
			else $url.="?return_forward=".$forward;
		}
		if(!empty($otherparams)){
			$url.="&".$otherparams;
		}
		echo "<script language=\"javascript\">window.open('".$url."','_self');</script>";
		exit;
	}

	function flash($url, $refer = null, $message=null, $result = 1, $pause=null, $back_list = null, $back_add = null)
	{
		if (empty($refer)) {
			
			$gourl[]="refer=".$_SERVER['REQUEST_URI'];
		}else{
			$refer = str_replace("./", "", $refer);
			$gourl[]="refer=".$refer;
		}
		if (!empty($message)) {
			$gourl[]="message=".urlencode($message);
		}
		if ($result) {
			$gourl[]="result=1";
		}
		if (!is_null($pause)) {
			$gourl[]="pause=".$pause;
		}
		if (!is_null($back_list)) {
			$gourl[]="listpage=".$back_list;
		}
		if (!is_null($back_add)) {
			$gourl[]="addpage=".$back_add;
		}
		$url_params = implode("&", $gourl);
		if(substr($url_params,0,1)=="&") $url_params = substr_replace($url_params, "", 0, 1);
		$url.= "?".$url_params;
		echo "<script language=\"javascript\">window.open('".$url."','_self');</script>";
		exit;
	}

	function createFolder($path)
	{
	   if (!file_exists($path))
	   {
	    createFolder(dirname($path));
	    mkdir($path, 0777);
	   }
	}

	function template($filename = null, $ext = ".html")
	{
		global $smarty;
		$return = false;
		$return = $smarty->display($filename.".html");
		return $return;
	}

	function getSepDays($date1,$date2)
	{
		$tmp = $date2 - $date1;
		$days = round($tmp/3600/24);
		return $days;
	}

	function ua_checkEmail($email){
		$return = false;
		if(strstr($email, '@') && strstr($email, '.')){
			if(eregi("^([_a-z0-9]+([\._a-z0-9-]+)*)@([a-z0-9]{2,}(\.[a-z0-9-]{2,})*\.[a-z]{2,3})$", $email)){
				$return = true;
			}
		}
		return $return;
	}

	function uaSetLoginSession($session_vars)
	{
		if (is_array($session_vars)) {
			foreach ($session_vars as $session_key=>$session_val) {
				$_SESSION[$session_key] = $session_val;
			}
		}
	}

	function uaSetLoginCookie($cookie_vars)
	{
		if (is_array($cookie_vars)) {
			foreach ($cookie_vars as $cookie_key=>$cookie_val) {
				$_COOKIE[$cookie_key] = $cookie_val;
			}
		}
	}

	function ua_checkLogin($username,$userpass,$url = null)
	{
		global $member,$company, $time_stamp, $forums;
		global $g_db;
		$keep_online = 3600;
		
    //$forward = $_GET['referer'] ? urldecode($_GET['referer']):URL;
    $forward = URL;
		
    if(!empty($url)) $forward = urldecode($url);
		$checked = $member->checkUserLogin($username,$userpass);
		if ($checked > 0) {
			$tmp_memberinfo = $member->getMemberInfo($username);
			uaSetLoginSession(array("MemberName"=>$username,"MemberID"=>$tmp_memberinfo['id'],"MemberPass"=>md5($userpass)));
			usetcookie("auth",
			authcode($tmp_memberinfo['id'], "ENCODE")."|".
			authcode($username, "ENCODE")."|".
			authcode(md5($userpass), "ENCODE")."|".
			authcode($tmp_memberinfo['user_type'], "ENCODE")."|".
			authcode($tmp_memberinfo['email'], "ENCODE")."|".
			authcode($tmp_memberinfo['user_level'], "ENCODE")."|".
			authcode($keep_online, "ENCODE")."|".
			authcode($tmp_memberinfo['credit_point'], "ENCODE"));
			$member_info = array
			(
			'time'		=> $time_stamp,
			'username'	=> $username,
			'password'	=> md5($userpass),
			'email'		=> $tmp_memberinfo['email'],
			);
			if($tmp_memberinfo['user_level'] == 9) {
				$member_info['isadmin'] = 1;
				$_SESSION['is_admin'] = $username;
			}
			if($forums['switch']==true){
				if($forums['type']=="discuz"){
					$member_info['cookietime'] = $keep_online;
					$goto_page = DZ_API($member_info,"login",$forward);
					header("Location:".$goto_page);
					exit;
				}elseif($forums['type']=="phpwind") {
					$member_info['uid'] = $tmp_memberinfo['id'];
					$member_info['cktime'] = $keep_online;
					$goto_page = PW_API($member_info,"login",$forward);
					header("Location:".$goto_page);
					exit;
				}
			}else{
				$goto_page = $forward;
				goto($goto_page);
				exit;
			}
			unset($tmp_memberinfo);
		}else{
			$errors = true;
		}
		return $checked;
	}

	/**
	* @para string $var cookie
	* @para string $value cookie
	* @para int $life 
	* @para int $prefix cookie
	*
	*/

	function usetcookie($var, $value, $life = 0, $prefix = 1) {
			global $cookiepre;
			$cookiedomain = ''; 			
			$cookiepath = '/';			
			$timestamp = time();
			setcookie(($prefix ? $cookiepre : '').$var, $value,
					$life ? $timestamp + $life : 0, $cookiepath,
					$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
	}

	function uclearcookies() {
		usetcookie('auth', '', -86400 * 365);
	}

	function fileext($filename) {
		return substr(($t=strrchr($filename,'.'))!==false?".".$t:'',1);
	}

	function uaDateCheck($ymd, $sep='-') {
		if(!empty($ymd)) {
			list($year, $month, $day) = explode($sep, $ymd);
			return checkdate($month, $day, $year);
		} else {
			return FALSE;
		}
	}

	function uaHtmlSpecialChars($string) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = uhtmlspecialchars($val);
			}
		} else {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
		}
		return $string;
	}

	function uaGetClientIP()
	{
		$ip = $_SERVER["REMOTE_ADDR"];
		$ip1 = $_SERVER["HTTP_X_FORWARDED_FOR"];
		if ($ip1) {
			$ip = $ip1;
		}
		return $ip;
	}

	function uaCheckMediaPath($image_path = null,$i_size = null)
	{
		if(is_null($image_path)) $image_path = "media".DS."products".DS;
		if(is_null($i_size)) $i_size = "big".DS;
		$pathname = gmdate("Ym").DS;
		$fullpath = BASE_DIR.$image_path."{$i_size}".$pathname;
		if (!file_exists($fullpath)) {
			$created = mkdir($fullpath,0777);
			if (!$created) {
				die("Error occured when upload picture !");
			}
		}
		return  $fullpath;
	}

	function uaAddSlashes($string, $force = 0) {
		if(get_magic_quotes_gpc() || $force) {
			if(is_array($string)) {
				foreach($string as $key => $val) {
					$string[$key] = addslashes($val, $force);
				}
			} else {
				$string = addslashes($string);
			}
		}
		return $string;
	}

	function uaDateConvert($access_date,$ds = "-")
	{
		$date_elements = explode($ds, $access_date);
		$s_time = mktime (0, 0, 0, $date_elements [1], $date_elements[2], $date_elements [0]);
		return $s_time;
	}

	function getmicrotime(){
	    list($usec, $sec) = explode(" ",microtime());
	    return ((float)$usec + (float)$sec);
    }

    function uaConvertComma($str){
		$str = strip_tags($str);
		if(strpos($str, "，")) $str = str_replace("，",",",uaAddSlashes($str));
		if(strpos($str, ",")) {
			$str = preg_replace("/\s*/","",$str);
			$str = str_replace(",", " ", $str);
		}else{
			$str = trim($str);
			$str = preg_replace("/\s(?=\s)/", "", $str);
			$str = preg_replace("/[\n\r\t]/", "", $str);
		}
		$str = str_replace(" ", ",", $str);
		return $str;
    }

    function uaProcessTableCol($colname)
    {
    	$new_column_name = null;
    	if (strstr($colname, "_")) {
    		$tmp_col = explode("_", $colname);
    		foreach ($tmp_col as $val) $new_column_name.=ucfirst(strtolower($val));
    	}else {
    		$new_column_name = ucfirst(strtolower($colname));
    	}
    	return $new_column_name;
    }

    function uaGetAbsoluteUrl()
    {
    	return "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    }

    function uaGetHost($http = true)
    {
    	if($http) {
			$return = "http://".$_SERVER['HTTP_HOST'];
		} else {
			$return = $_SERVER['HTTP_HOST'];
		}
    	return $return;
    }

    function uatrim(&$val)
	{
		$val = strip_tags(trim($val));
	}

    function uaGetOs() {
    	$os = $_SERVER['HTTP_USER_AGENT'];
    	if(strpos($os,"Windows")) $os="Windows";
    	elseif(strpos($os,"unix")) $os="Unix";
    	elseif(strpos($os,"linux")) $os="Linux";
    	elseif(strpos($os,"SunOS")) $os="SunOS";
    	elseif(strpos($os,"BSD")) $os="FreeBSD";
    	elseif(strpos($os,"Mac")) $os="Mac";
    	else $os="Other";
    	return $os;
    }

	function run($sql) {
		global $dbcharset, $tb_prefix;
		$sql = str_replace("\r", "\n", str_replace(' eos_', ' '.$tb_prefix, $sql));
		$ret = array();
		$num = 0;
		foreach(explode(";\n", trim($sql)) as $query) {
			$queries = explode("\n", trim($query));
			foreach($queries as $query) {
				$ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
			}
			$num++;
		}
		unset($sql);

		foreach($ret as $query) {
			$query = trim($query);
			if($query) {
				if(substr($query, 0, 12) == 'CREATE TABLE') {
					$name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
					mysql_query(createtable($query, $dbcharset));
				} else {
					mysql_query($query);
				}
			}
		}
	}

	function createtable($sql, $dbcharset) {
		$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
		$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
		return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
			(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
	}

	function uaCheckAdminSession()
	{
		if(empty($_SESSION['admin']['current_adminer']) || empty($_SESSION['admin']['current_pass'])){
			goto("login.php");
		}else{
			require("../".APP_NAME.'lang/adminer.inc.php');
			setvar("AdminLangAction", $cfg['action']);
		}
	}

	function SplitKeywords($params)
	{
		extract($params);
		$links = null;
		$keywords = explode(",",$params['keyword']);
		foreach ($keywords as $key=>$val) {
			$links.="<a href='".URL."tag/search.php?keyword=".urlencode($val)."'>".$val."</a>&nbsp;";
		}
		return $links;
	}

	function nextIndustry($sid)
	{
		global $industry;
		global $subs;
		$nextsubs = array_slice($subs,21,20);
		$nextsubs = $industry->formatSubIndusty($nextsubs);
	    $obj = new xajaxResponse();
	    $obj->addAssign("divSubIndustry","innerHTML", $industry->subHeader.$nextsubs.$industry->subFooter);
	    return $obj->getXML();
	}

	function loadDivSubIndustry($sid, $li = null)
	{
		global $industry;
		$li = (is_null($li))?1:intval($li);
		$subs = $industry->getAllIndustry("AND Industry.parentid=".$sid);
		$model_subs = $industry->formatSubIndusty($subs,$li);
	    $obj = new xajaxResponse();
	    $obj->addAssign("divSubIndustry","innerHTML", $industry->subHeader.$model_subs.$industry->subFooter);
	    return $obj->getXML();
	}

	function uaFormatPositionPath($position_path)
	{
		$position_name = null;
		if(is_array($position_path)){
			foreach ($position_path as $key=>$val) {
				$position_name.="<a href=\"".$val['url']."\">".$val['name']."</a>";
			}
		}
		return $position_name;
	}

	function uses() {
		$args = func_get_args();
		foreach($args as $arg) {
			$class_name = strtolower($arg);
			require(LIB_PATH . "controllers/".$class_name. '_controller.php');
			require(LIB_PATH . "models/".$class_name. '.php');
		}
	}

	function uaIp2Long($ip)
	{
		return sprintf("%u",ip2long($ip));
	}

	function table2sql($table){
		global $db;
		$tabledump = "DROP TABLE IF EXISTS $table;\n";
		$createtable = $db->query("SHOW CREATE TABLE $table");
		if($db->next_record()){
			$create = $db->f("Create Table");
			$tabledump.= $create.";\n\n";
		}
		return $tabledump;
	}

	function data2sql($table)
	{
		global $db;
		$tabledump = table2sql($table);

		$rows = $db->query("SELECT * FROM $table");
		$nums = $db->affected_rows();
		$numfields = $db->num_fields();
		while ($row = mysql_fetch_row($rows))
		{
			$comma = "";
			$tabledump .= "INSERT INTO $table VALUES(";
			for($i = 0; $i < $numfields; $i++)
			{
				$tabledump .= $comma."'".mysql_escape_string($row[$i])."'";
				$comma = ",";
			}
			$tabledump .= ");\n";
		}
		$tabledump .= "\n";
		return $tabledump;
	}

	function uaLog($action_name = null,  $type_id = 1, $member_id = null, $action_result = true)
	{
		global $log;
		$vals = array();
		
		return true;
	}

	function plugin(){
		return false;
	}

	function checkEmail($str)
	{
		if (eregi("^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$", $str))
		return true;
		else
		return false;
	}

   function isUrl($inputUrl){
       $regUrl = "^(http://)?((localhost)|(([0-9a-z][0-9a-z_-]+.){1,3}[a-z]{2,4}))$";
       $resultUrl = ereg($regUrl,$inputUrl);
       if ($resultUrl == 1)
           {return "true";}
       else
           {return "false";}
   }

	
	
	function editor($input_name, $input_value, $smartyOutput, $toolbar = "Default")
	{
		
		$editor = new FCKeditor($input_name) ;
		$editor->BasePath   = "./fckeditor/";
		$editor->ToolbarSet = $toolbar;
		$editor->Width      = "100%";
		$editor->Height     = "200";
		$editor->Value      = $input_value;
		$oFCKeditor->InstanceName = $smartyOutput;
		$FCKeditor = $editor->CreateHtml();
		setvar($smartyOutput, $FCKeditor);
	}

	
	function stripSeqSpace($string)
	{
		$str = preg_replace('#\s+#', ' ', trim($string));
		return $str;
	}

	function logadmin($result = true){
		global $adminlog;
		global $time_stamp;
		global $data;
		if(!empty($data['Adminlog'])) {
			if(!isset($data['Adminlog']['adminer_id'])) $data['Adminlog']['adminer_id'] = $_SESSION['admin']['current_adminer_id'];
			if(!isset($data['Adminlog']['created'])) $data['Adminlog']['created'] = $time_stamp;
			if(!isset($data['Adminlog']['ip_address'])) $data['Adminlog']['ip_address'] = uaIp2Long(uaGetClientIP());
			$result = $adminlog->save($data['Adminlog']);
		}
		return $result;
	}

	function getMemberInfo()
	{
		global $cookiepre;
		$ua_member = null;
		if (!empty($_COOKIE[$cookiepre."auth"])) {
			$ua_member_str = explode("|", $_COOKIE[$cookiepre."auth"]);
			$ua_member['id'] 			= authcode($ua_member_str[0], "DECODE");
			$ua_member['username']		= authcode($ua_member_str[1], "DECODE");
			$ua_member['userpass']		= authcode($ua_member_str[2], "DECODE");
			$ua_member['user_type']		= authcode($ua_member_str[3], "DECODE");
			$ua_member['email']			= authcode($ua_member_str[4], "DECODE");
			$ua_member['user_level']	= authcode($ua_member_str[5], "DECODE");
			$ua_member['keep_online']	= authcode($ua_member_str[6], "DECODE");
			$ua_member['credit_point']	= authcode($ua_member_str[7], "DECODE");
		}else {
			
		}
		return $ua_member;
	}

	function authcode($string, $operation, $key = '') {

		$key = md5($key ? $key : AUTH_KEY);
		$key_length = strlen($key);

		$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
		$string_length = strlen($string);

		$rndkey = $box = array();
		$result = '';

		for($i = 0; $i <= 255; $i++) {
			$rndkey[$i] = ord($key[$i % $key_length]);
			$box[$i] = $i;
		}

		for($j = $i = 0; $i < 256; $i++) {
			$j = ($j + $box[$i] + $rndkey[$i]) % 256;
			$tmp = $box[$i];
			$box[$i] = $box[$j];
			$box[$j] = $tmp;
		}

		for($a = $j = $i = 0; $i < $string_length; $i++) {
			$a = ($a + 1) % 256;
			$j = ($j + $box[$a]) % 256;
			$tmp = $box[$a];
			$box[$a] = $box[$j];
			$box[$j] = $tmp;
			$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}

		if($operation == 'DECODE') {
			if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
				return substr($result, 8);
			} else {
				return '';
			}
		} else {
			return str_replace('=', '', base64_encode($result));
		}

	}

	function setPosition($seperate = " > ", $home = true){
		global $positions, $nav;
		$return = array();
		if($home){
			$positions[1] = "<a href='".URL."' title=''>".$nav[0]['cname']."</a>";
		}
		ksort($positions);
		$return = implode($seperate, $positions);
		return $return;
	}

	function dir_writeable($dir) {
		if(!is_dir($dir)) {
			@mkdir($dir, 0777);
		}
		if(is_dir($dir)) {
			if($fp = @fopen("$dir/ua_sample.txt", 'w')) {
				@fclose($fp);
				@unlink("$dir/ua_sample.txt");
				$writeable = true;
			} else {
				$writeable = false;
			}
		}
		return $writeable;
	}

	function splitIndustryAmount($params)
	{
		extract($params);
		$str = $params['amount_str'];
		$tmp1 = explode("|", $str);
		$type = $params['amount_type'];
		$tmp1 = explode("|", $str);
		if ($type=="sum") {
			return intval(array_sum($tmp1));
		}else{
			$type_t = intval($type)-1;
			return $tmp1[$type_t];
		}
	}


	function uaIndustryMain($type = 1)
	{
		global $industry;
		$res = $industry->getAllIndustry(" AND Industry.parentid=0");
		foreach ($res as $key=>$val) {
			if($type == 2){
				echo "<option value=".$val['ID'];
				if($val['ID'] == $_GET['pid']) echo " selected";
				echo ">".$val['Name']."</option>\n";
				echo uaIndustrySub($val['ID'],"--",$type);
			}elseif($type == 1){
				echo "<ul><li><a href='#' onclick=\"toggleMenu('submenuid".$val['ID']."'); return false;\" class=\"listhead\">".$val['Name']."</a>";
				echo "<a href='./industry.php?action=mod&id=".$val['ID']."&pid=".$val['ParentID']."'>修改</a>&nbsp;&nbsp;";
				echo "<a href='./industry.php?action=del&id=".$val['ID']."'>删除</a>&nbsp;&nbsp;";
				echo "<a href='./industry.php?action=mod&pid=".$val['ID']."'>添加子类别</a>&nbsp;&nbsp;";
				echo "<a href='./industry.php?action=del&pid=".$val['ID']."'>清空该大类下所有子类</a>";
				echo "<ul class=\"expanded\" id=\"submenuid".$val['ID']."\">";
				echo uaIndustrySub($val['ID'],"",$type);
				echo "</li>";
				echo "</ul>";
			}elseif($type == 3){
				//
			}
		}
	}

	function uaIndustrySub($fid,$strdis,$type = 1)
	{
		global $industry;
		$res1 = $industry->getAllIndustry(" AND Industry.parentid=".$fid);
		foreach ($res1 as $key1=>$val1) {
			if($type == 2){
				echo "<option value=".$val1['ID'];
				if($val1['ID'] == $_GET['pid']) echo " selected";
				echo ">".$strdis.$val1['Name']."</option>\n";
				uaIndustrySub($val1['ID'],$strdis.$strdis,$type);
			}else {
				echo "<li><a href=\"#\">";
				echo $val1['Name'];
				echo "</a><div class='action'><a href='./industry.php?action=mod&id=".$val1['ID']."&pid=".$val1['ParentID']."'>修改</a>&nbsp;<a href='./industry.php?action=del&id=".$val1['ID']."'>删除</a>&nbsp;<a href='./industry.php?action=mod&pid=".$val1['ID']."'>添加子类别</a></div>";
				echo "<ul class=\"expanded\"><li>";
				uaIndustrySub($val1['ID'],"",$type);
				echo "</li></ul>";
				echo "</li>";
			}
		}
	}
?>
